<template>
  <el-row class="user-info-form" type="flex" justify="center">
    <el-col>
      <el-form label-position="top" :model="userInfoForm" :rules="userInfoFormRules" ref="userInfoForm" @submit.native.prevent>
        <input type="hidden" value="userId" id="userId" v-model="userInfoForm.id" />
        <el-form-item label="账号：" prop="accountName">
          <el-input v-model="userInfoForm.accountName" auto-complete="off" placeholder="请输入账号" :disabled="!!userInfoForm.id"></el-input>
          <span class="color-2">规则：2~16位英文、“-”、“_”或数字&nbsp;&nbsp;&nbsp;&nbsp;不允许有空格&nbsp;&nbsp;&nbsp;&nbsp;不允许有中文</span>
        </el-form-item>
        <el-form-item label="姓名：" prop="name">
          <el-input v-model="userInfoForm.name" auto-complete="off" placeholder="请输入姓名"></el-input>
        </el-form-item>
        <el-form-item label="职位：" prop="postName">
          <el-input v-model="userInfoForm.postName" auto-complete="off" placeholder="请输入职位"></el-input>
        </el-form-item>
        <el-form-item label="用户所属组织/单位：" prop="selfOrgId">
          <tree-select
            class="self-org-tree"
            v-model="userInfoForm.selfOrgId"
            filterable
            :width="536"
            :data="orgList"
            :defaultProps="orgDefaultProps"
            :nodeKey="orgNodeKey"
            :checkedKeys="checkedOrgKeys"
            @popoverHide="orgPopoverHide"
          ></tree-select>
        </el-form-item>
        <el-form-item label="建筑物权限分配：" prop="buildIds" v-if="buildList.length > 0">
          <tree-select
            v-model="userInfoForm.buildIds"
            filterable
            :width="536"
            :data="buildList"
            :defaultProps="buildDefaultProps"
            :checkedKeys="checkedBuildKeys"
            :nodeKey="buildNodeKey"
          ></tree-select>
        </el-form-item>
        <el-form-item label="手机号：" prop="tel">
          <el-input v-model="userInfoForm.tel" auto-complete="off" placeholder="请输入手机号"></el-input>
        </el-form-item>
        <el-form-item class="multi-line" label="用户所属角色和管理的联网单位：">
          <div class="multi-line-form" v-for="(item, i) in userRoleUnitList" :key="item.id">
            <tree-select
              v-model="item.roleId"
              placeholder="请先选择角色"
              filterable
              :width="200"
              :data="item.roleList"
              :defaultProps="roleDefaultProps"
              :checkedKeys="item.checkedRoleId"
              :nodeKey="roleNodeKey"
              :index="String(i)"
              @popoverHide="rolePopoverHide"
            ></tree-select>
            <tree-select
              class="self-org-tree"
              v-model="item.orgIds"
              filterable
              multiple
              placeholder="请选择联网单位"
              :width="200"
              :data="item.orgList"
              :defaultProps="orgDefaultProps"
              :checkedKeys="item.checkedOrgIds"
              :nodeKey="orgNodeKey"
            ></tree-select>
          </div>
          <div class="multi-line-button">
            <!-- <el-button type="info" icon="el-icon-plus" circle size="small" @click="addMultiLineForm"></el-button> -->
            <el-button type="info" icon="el-icon-delete" circle size="small" v-if="userRoleUnitList.length > 1" @click="deleteMultiLineForm"></el-button>
          </div>
        </el-form-item>
        <span class="color-4">初始密码：{{defaultPassword || 'wwhl123456'}}</span>
        <el-form-item label-width="0" class="verifyidentity-button">
          <el-button round @click="closeUserInfo">取消</el-button>
          <el-button type="primary" round @click="addUser('userInfoForm')">确定</el-button>
        </el-form-item>
      </el-form>
    </el-col>
  </el-row>
</template>

<script>
import TreeSelect from '@/libs/TreeSelect/Main'
import { validphone, isvalidUsername } from '@/utils/validate'
import {
  getUcOrgList,
  getFbsTree,
  updateUserInfo,
  getRoleOrgByAccount,
  getRoleAuthList,
} from '@/api/sysConfig'
import { getDefaultPassword } from '@/api/user'
import { setTimeout } from 'timers'

export default {
  name: 'UserInfoMaintain',
  components: {
    TreeSelect,
  },
  props: {
    userInfo: {
      type: Object,
      required: false,
    },
    orgList: {
      type: Array,
      required: true,
    },
    roleList: {
      type: Array,
      required: true,
    },
    closeUserInfo: {
      type: Function,
      required: true,
    },
  },
  data() {
    const validatePhoneNum = (rule, value, callback) => {
      if (!validphone(value)) callback(new Error('请输入正确的手机号'))
      callback()
    }
    const validateUsername = (rule, value, callback) => {
      if (!isvalidUsername(value)) {
        callback(new Error('请输入正确的账号'))
      } else if (value.length < 2 || value.length > 16) {
        callback(new Error('账号长度2~16位'))
      } else {
        callback()
      }
    }
    return {
      defaultPassword: '',
      orgDefaultProps: {
        children: 'nodes',
        label: 'name',
        value: 'id',
      },
      orgNodeKey: 'id',
      checkedOrgKeys: [], // 默认选中的
      buildList: [],
      buildDefaultProps: {
        children: 'nodes',
        label: 'text',
        value: 'id',
      },
      buildNodeKey: 'id',
      checkedBuildKeys: [], // 默认选中的
      userInfoForm: {
        id: '',
        accountName: '', // 账号
        name: '', // 姓名
        postName: '', // 职位
        selfOrgId: '', // 用户所属组织/单位
        buildIds: '', // 建筑物编号
        tel: '',
      },
      userInfoFormRules: {
        accountName: [
          { required: true, trigger: 'blur', validator: validateUsername },
        ],
        name: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
        selfOrgId: [
          {
            required: true,
            message: '请选择用户所属组织/单位',
            trigger: 'blur',
          },
        ],
        tel: [
          {
            required: true,
            validator: validatePhoneNum,
            trigger: ['blur', 'change'],
          },
        ],
        postName: [{ required: true, message: '请输入职位', trigger: 'blur' }],
      },
      roleDefaultProps: {
        children: 'nodes',
        label: 'name',
        value: 'id',
      },
      roleNodeKey: 'id',
      userRoleUnitList: [
        {
          id: '1',
          roleId: '',
          roleList: [],
          orgIds: '',
          orgList: [],
          checkedOrgIds: [], // 默认选中的值
          checkedRoleId: [], // 默认选中的值
        },
      ], // 编辑时角色和联网单位关系
      multiLineNum: 1,
    }
  },
  created() {
    let userInfoObj = this.userInfo
    this.getInitPassword()
    this.$nextTick(() => {
      if (userInfoObj.userId) {
        this.userInfoForm.id = userInfoObj.userId
        this.userInfoForm.accountName = userInfoObj.accountName
        this.userInfoForm.name = userInfoObj.name
        this.userInfoForm.postName = userInfoObj.postName
        if (userInfoObj.organizationId) {
          this.userInfoForm.selfOrgId = userInfoObj.organizationId
        }
        if (userInfoObj.organizationId) {
          this.userInfoForm.buildIds = userInfoObj.buildIds
        }
        this.userInfoForm.tel = userInfoObj.phone
        this.checkedOrgKeys = String(userInfoObj.organizationId).split(',')
        this.checkedBuildKeys = String(userInfoObj.buildIds).split(',')
        this.bindSelectFbs(userInfoObj.organizationId)
        this.echoRoleOrg(userInfoObj.accountName, userInfoObj.organizationId)
      }
      this.userInfoFormRules.selfOrgId[0].trigger = 'change'
      // 处理业主单位选项禁用（恶心）
      setTimeout(() => {
        let $arr = $('.self-org-tree .el-tree-node__label')
        for (var j = 0; j < $arr.length; j++) {
          if (
            $arr[j].textContent === '业主单位' ||
            $arr[j].textContent === '联网单位'
          ) {
            $($arr[j]).addClass('is-disabled')
          }
        }
      }, 1000)
    })
  },
  methods: {
    // 获取初始密码
    getInitPassword() {
      let that = this
      getDefaultPassword().then((res) => {
        if (res.status === 200) {
          that.defaultPassword = res.data
        }
      })
    },
    // 处理联网单位，id=73的增加disabled
    detailOrgData(data) {
      let arr = data
      for (let i = 0, len = arr.length; i < len; i++) {
        if (arr[i].id == 73) {
          arr[i].disabled = true
        }
      }
      // 处理业主单位选项禁用（恶心）
      setTimeout(() => {
        let $arr = $('.self-org-tree .el-tree-node__label')

        for (var j = 0; j < $arr.length; j++) {
          if (
            $arr[j].textContent === '业主单位' ||
            $arr[j].textContent === '联网单位'
          ) {
            $($arr[j]).addClass('is-disabled')
          }
        }
      }, 1000)
      return arr
    },
    // 获取角色和联网单位关系
    setUserRoleUnitStr() {
      let arr = this.userRoleUnitList
      let newArr = []
      for (var i = 0, len = arr.length; i < len; i++) {
        if (typeof arr[i].orgIds === 'string') {
          let rogList = arr[i].orgIds.split(',')
          if (arr[i].orgIds.indexOf(73) > -1) {
            rogList.splice(rogList.indexOf('73'), 1)
            arr[i].orgIds = rogList.join(',')
          }
        } else {
          if (arr[i].orgIds.indexOf(73) > -1) {
            arr[i].orgIds.splice(arr[i].orgIds.indexOf(73), 1)
          }
        }
        newArr.push({
          roleId: arr[i].roleId,
          orgIds:
            typeof arr[i].orgIds === 'string'
              ? arr[i].orgIds
              : arr[i].orgIds.join(','),
        })
      }
      return JSON.stringify(newArr)
    },
    // 增加新用户
    addUser(formName) {
      // 阻止事件冒泡
      event.stopPropagation()
      let that = this
      that.$refs[formName].validate((valid) => {
        if (valid) {
          // 检测角色和单位是否有数据
          if (
            that.userRoleUnitList.length > 0 &&
            that.userRoleUnitList[0].roleId != '' &&
            (typeof that.userRoleUnitList[0].orgIds === 'string'
              ? that.userRoleUnitList[0].orgIds != ''
              : that.userRoleUnitList[0].orgIds.length > 0)
          ) {
            let parames = that.userInfoForm
            // 组装角色和单位关系数据
            parames.userRoleUnitStr = that.setUserRoleUnitStr()
            // 提交
            updateUserInfo(parames).then((res) => {
              if (res.status === 200) {
                that.$message({
                  message: '保存成功！',
                  type: 'success',
                })
                that.closeUserInfo(true)
              } else {
                that.$message({
                  message: res.info,
                  type: 'warning',
                })
              }
            })
          } else {
            that.$message({
              message: '请选择用户所属角色和管理的联网单位',
              type: 'warning',
            })
          }
        } else {
          return false
        }
      })
    },
    // 选择了用户所属组织/单位
    orgPopoverHide(checkedIds, checkedData) {
      // 用户所属组织选择值变化
      if (checkedIds && checkedIds !== this.userInfoForm.selfOrgId) {
        // 初始化建筑物值
        this.userInfoForm.buildIds = ''
        this.checkedBuildKeys = []
        // 重新绑定建筑物下拉框数据
        this.bindSelectFbs(checkedIds)
        // 初始化多行表单
        this.userRoleUnitList = []
        this.multiLineNum = 0
        this.addMultiLineForm(checkedIds)
      }
    },
    // 查询消防建筑物结构树
    bindSelectFbs(checkedIds) {
      var that = this
      if (checkedIds) {
        getFbsTree({
          organizationId: checkedIds,
        }).then((res) => {
          // var res = {"status":200,"info":"操作成功","total":1,"data":[{"indoorId":"","nodes":[{"indoorId":"","nodes":null,"layeredGraphUrl":"https://img.kdlayun.com/layer/layerPic_1517308096109.png","isAddLayeredGraph":1,"id":519,"sort":0,"text":"东一层","parentId":518,"tags":""},{"indoorId":"","nodes":null,"layeredGraphUrl":"https://img.kdlayun.com/layer/layerPic_1517308243087.png","isAddLayeredGraph":1,"id":520,"sort":0,"text":"一中庭","parentId":518,"tags":""},{"indoorId":"","nodes":null,"layeredGraphUrl":"https://img.kdlayun.com/layer/layerPic_1517308407201.png","isAddLayeredGraph":1,"id":522,"sort":0,"text":"西一层","parentId":518,"tags":""},{"indoorId":"","nodes":null,"layeredGraphUrl":"https://img.kdlayun.com/layer/layerPic_1517308523671.png","isAddLayeredGraph":1,"id":523,"sort":0,"text":"东二层","parentId":518,"tags":""},{"indoorId":"","nodes":null,"layeredGraphUrl":"https://img.kdlayun.com/layer/layerPic_1517308908170.png","isAddLayeredGraph":1,"id":524,"sort":0,"text":"西二层","parentId":518,"tags":""},{"indoorId":"","nodes":null,"layeredGraphUrl":"https://img.kdlayun.com/layer/layerPic_1517309564915.png","isAddLayeredGraph":1,"id":525,"sort":0,"text":"地下出口厅","parentId":518,"tags":""},{"indoorId":"","nodes":null,"layeredGraphUrl":"https://img.kdlayun.com/layer/layerPic_1517309269772.png","isAddLayeredGraph":1,"id":526,"sort":0,"text":"夹层","parentId":518,"tags":""}],"layeredGraphUrl":"https://img.kdlayun.com/layer/layerPic_1517918087785.png","isAddLayeredGraph":0,"id":518,"sort":0,"text":"南京站北站房","parentId":0,"tags":""}]}
          if (res.status === 200 && res.data.length > 0) {
            that.buildList = res.data
          } else {
            that.buildList = []
          }
        })
      }
    },
    // 根据选择的组织单位获取角色信息
    /*
     * 【参数说明】
     *    orgId：用户所属组织/单位编码，作为查询参数
     *        i：当前操作的多行表单排序号，从0开始算
     *  isReset：是否为重置下拉框数据
     *     data：赋值数据
     */
    bindSelectRole(orgId, i, isReset, data) {
      let that = this
      getRoleAuthList({
        orgId: orgId || '',
      }).then((res) => {
        if (isReset) {
          // 初始化角色选择框
          that.userRoleUnitList[i].roleList = res.data
          that.userRoleUnitList[i].roleId = ''
          that.userRoleUnitList[i].checkedRoleId = []
        } else {
          that.userRoleUnitList[i].roleList = res.data
          that.userRoleUnitList[i].roleId = data || ''
          that.$nextTick(() => {
            that.userRoleUnitList[i].checkedRoleId = data
              ? String(data).split(',')
              : []
          })
        }
      })
    },
    // 根据选择的角色获取联网单位
    /*
     * 【参数说明】
     *   roleId：多行表单当前行选择的角色id，作为查询参数
     *    orgId：用户所属组织/单位编码，作为查询参数
     *        i：当前操作的多行表单排序号，从0开始算
     *  isReset：是否为重置下拉框数据
     *     data：赋值数据
     */
    bindSelectRoleOrg(roleId, orgId, i, isReset, data) {
      var that = this
      getUcOrgList({
        roleId: roleId,
        orgId: orgId,
      }).then((res) => {
        if (isReset) {
          // 初始化单位选择框
          that.userRoleUnitList[i].orgList = that.detailOrgData(res.data)
          that.userRoleUnitList[i].orgIds = ''
          that.$nextTick(() => {
            that.userRoleUnitList[i].checkedOrgIds = []
          })
        } else {
          that.userRoleUnitList[i].orgList = that.detailOrgData(res.data)
          that.userRoleUnitList[i].orgIds = data || ''
          that.$nextTick(() => {
            that.userRoleUnitList[i].checkedOrgIds = data
              ? String(data).split(',')
              : []
          })
        }
      })
    },
    // 选择了角色
    rolePopoverHide(checkedIds, checkedData) {
      if (checkedIds && event.currentTarget.offsetParent) {
        let index = event.currentTarget.offsetParent.getAttribute('data-index') // 操作的多行表单对应序号

        // 角色选择值变化
        if (checkedIds && checkedIds != this.userRoleUnitList[index].roleId) {
          // 重新绑定建筑物下拉框数据
          this.bindSelectRoleOrg(
            checkedIds,
            this.userInfoForm.selfOrgId,
            index,
            true
          )
        }
      }
    },
    //编辑回显联网单位和角色
    echoRoleOrg(account, orgId) {
      var that = this
      getRoleOrgByAccount({
        account: account,
      }).then((res) => {
        let arr = res.data
        // 重置多行表单
        that.multiLineNum = 0
        that.userRoleUnitList = []
        for (var i = 0, len = arr.length; i < len; i++) {
          // 添加一行数据
          that.addMultiLineForm(that.userInfo.organizationId, () => {
            // 绑定角色下拉框数据，并赋值
            that.bindSelectRole(orgId, i, false, arr[i].roleId)
            // 绑定联网单位下拉框数据，并赋值
            that.bindSelectRoleOrg(
              arr[i].roleId,
              orgId,
              i,
              false,
              arr[i].orgIds
            )
          })
        }
        if (arr.length == 0) {
          that.addMultiLineForm(that.userInfo.organizationId)
        }
      })
    },
    // 增加一行角色和单位关系
    addMultiLineForm(orgId, callback) {
      this.multiLineNum += 1
      let newObj = {
        id: this.multiLineNum,
        orgIds: '',
        orgList: [],
        roleId: '',
        roleList: [],
        checkedOrgIds: [],
        checkedRoleId: [],
      }
      this.userRoleUnitList.push(newObj)
      if (callback && typeof callback === 'function') {
        callback()
      } else {
        // 获取角色信息
        this.bindSelectRole(orgId, this.multiLineNum - 1, true)
      }
    },
    // 删除一行角色和单位关系
    deleteMultiLineForm() {
      this.userRoleUnitList.pop()
      this.multiLineNum -= 1
    },
  },
}
</script>
